/**
 * Utility helper functions for TypeScript project.
 */

import { readFile, access, constants } from 'fs/promises';
import { extname } from 'path';

export function setupLogging(verbose: boolean = false): void {
  if (verbose) {
    console.log('Verbose logging enabled');
  }
  // In a real implementation, this would configure a logging library
}

export async function validateInput(filePath: string): Promise<boolean> {
  try {
    await access(filePath, constants.F_OK | constants.R_OK);
    return true;
  } catch (error) {
    return false;
  }
}

export async function readFileSafely(filePath: string): Promise<string> {
  try {
    return await readFile(filePath, 'utf-8');
  } catch (error) {
    // Try with different encoding if UTF-8 fails
    try {
      return await readFile(filePath, 'latin1');
    } catch (fallbackError) {
      throw new Error(`Failed to read file ${filePath}: ${fallbackError}`);
    }
  }
}

export async function ensureDirectory(dirPath: string): Promise<void> {
  const fs = await import('fs/promises');
  await fs.mkdir(dirPath, { recursive: true });
}

export function getFileExtension(filePath: string): string | null {
  try {
    return extname(filePath).toLowerCase();
  } catch (error) {
    return null;
  }
}

export function debounce<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: NodeJS.Timeout;
  
  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func(...args), delay);
  };
}

export async function retry<T>(
  operation: () => Promise<T>,
  maxAttempts: number = 3,
  delay: number = 1000
): Promise<T> {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await operation();
    } catch (error) {
      if (attempt === maxAttempts) {
        throw error;
      }
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  
  throw new Error('Should not reach here');
}